package com.dt.scheduled;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@EnableScheduling //开启定时任务注解
public class ScheduledTest implements SchedulingConfigurer {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTest.class);

    @Value("${scheduled.task.cron}")
    private String cronString;

    private static String strDateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(() -> log.info("间隔时间：" + cronString),
                triggerContext -> {
                    log.info("当前时间:" + dateFormat.format(new Date()));
                    return new CronTrigger(cronString).nextExecutionTime(triggerContext);
                }
        );
    }
}
